package cn.xsly.ymcc.service.impl;

import cn.xsly.ymcc.constants.Constants;
import cn.xsly.ymcc.domain.CourseType;
import cn.xsly.ymcc.dto.CrumbsDto;
import cn.xsly.ymcc.mapper.CourseTypeMapper;
import cn.xsly.ymcc.service.ICourseTypeService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程目录 服务实现类
 * </p>
 *
 * @author whale
 * @since 2022-10-23
 */
@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {


    @Override
    @Cacheable(cacheNames = Constants.COURSE_TYPE, key = "'all'")
    public List<CourseType> treeData() {
        /*//第一种
        List<CourseType> courseTypes = selectList(null);
        Map<String, List<CourseType>> groupByParentIdMap = courseTypes.stream().collect(Collectors.groupingBy(item -> item.getPath() == null ? "" : Objects.toString(item.getPid())));
        Map<String, CourseType> dataMap = courseTypes.stream().collect(Collectors.toMap(item -> item.getId().toString(), t -> t));
        List<CourseType> resp = Lists.newArrayList();
        groupByParentIdMap.forEach((parentId, values) -> {
            if (dataMap.containsKey(parentId)) {
                List<CourseType> child = dataMap.get(parentId).getChildren();
                if (CollUtil.isEmpty(child)) {
                    child = Lists.newArrayList();
                }
                child.addAll(values);
                dataMap.get(parentId).setChildren(child);
            } else {
                resp.addAll(values);
            }
        });
        return resp;
    }*/
        //1.查询出所有的数据
        List<CourseType> courseTypes = selectList(null);
        //2.把数据转换为Map<Long,CourseType>
        Map<Long, CourseType> map = courseTypes.stream().collect(Collectors.toMap(CourseType::getId, CourseType -> CourseType));
       /* Map<Long, CourseType> collect1 = courseTypes.stream().collect(Collectors.toMap(CourseType::getId
           , new Function<CourseType, CourseType>() {
               @Override
               public CourseType apply(CourseType courseType) {
                   return courseType;
               }
           }
        );*/

        //3.准备一个集合，装第一层CourseType
        List<CourseType> firstCourseType = new ArrayList<>();
        courseTypes.forEach(courseType -> {
            if (courseType.getPid() == null || courseType.getPid() == 0) {
                //就是顶层的分类
                firstCourseType.add(courseType);
            } else {
                //4.不是顶层分类，根据pid找到父级，把自己添加到父级的children里面
                CourseType parent = map.get(courseType.getPid());
                if (parent != null) parent.getChildren().add(courseType);
            }
        });
        return firstCourseType;
    }

    @Override
    public List<CrumbsDto> crumbs(Long courseTypeId) {
        CourseType courseType = selectById(courseTypeId);
        List<CrumbsDto> crumbs = new ArrayList<>();
        CrumbsDto firsts = new CrumbsDto();


        if (courseType.getPid() == 0) {
            firsts.setOwnerProductType(courseType);
            Wrapper<CourseType> wrapper = new EntityWrapper<>();
            wrapper.eq("pid", courseType.getPid());
            List<CourseType> sameParent = selectList(wrapper);
            firsts.setOtherProductTypes(sameParent);
            crumbs.add(firsts);
            return crumbs;
        } //不是顶级目录时，分割path
        String path = courseType.getPath();
        String[] split = path.split("\\.");
        for (String index : split) {
            CrumbsDto crumb = new CrumbsDto();
            CourseType courseTypeInFor = selectById(index);
            Wrapper<CourseType> conditionInFor = new EntityWrapper<>();
            conditionInFor.eq("pid", courseTypeInFor.getPid());
            List<CourseType> courseTypesInFor = selectList(conditionInFor);
            crumb.setOwnerProductType(courseTypeInFor);
            crumb.setOtherProductTypes(courseTypesInFor);
            crumbs.add(crumb);
        }
        return crumbs;

    }

    @Override
    @CacheEvict(cacheNames = Constants.COURSE_TYPE, key = "'all'")
    public boolean insert(CourseType entity) {
        return super.insert(entity);
    }

    @Override
    @CacheEvict(cacheNames = Constants.COURSE_TYPE, key = "'all'")
    public boolean deleteById(Serializable id) {
        return super.deleteById(id);
    }

    @Override
    @CacheEvict(cacheNames = Constants.COURSE_TYPE, key = "'all'")
    public boolean updateById(CourseType entity) {
        return super.updateById(entity);
    }
}

